package com.team8.user.pojo.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.team8.common.results.PageResult;
import com.team8.common.results.Result;
import com.team8.common.utils.NumberUtils;
import com.team8.user.pojo.User;
import com.team8.user.pojo.dao.UserDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserDao userdao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    static final String KEY_PREFIX = "user:code:email:";

    public Result insert(User user, String verifyCode) {

        String verifyCodeFromRedis = this.redisTemplate.opsForValue().get(KEY_PREFIX + user.getEmail());
        if(verifyCodeFromRedis == null || verifyCode == null || !verifyCode.equals(verifyCodeFromRedis))
            return new Result("verifyCode error!");

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("email", user.getEmail());

        List<User> users = userdao.selectByExample(example);

        if(!CollectionUtils.isEmpty(users))
            return new Result("email has existed");
        int insert = userdao.insert(user);
        redisTemplate.delete(KEY_PREFIX + user.getEmail());
        return new Result(200, "ok");
    }

    public Result insert(User user) {

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("email", user.getEmail());

        List<User> users = userdao.selectByExample(example);

        if(!CollectionUtils.isEmpty(users))
            return new Result("email has existed");
        int insert = userdao.insert(user);
        return new Result(200, "ok");
    }

    public Result insertDiqin(User user) {

        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("email", user.getEmail());

        List<User> users = userdao.selectByExample(example);

        if(!CollectionUtils.isEmpty(users))
            return new Result("email has existed");
        int insert = userdao.insert(user);
        return new Result("ok");
    }

    public User queryUser(String email, String pwd){
        Example example = new Example(User.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("email", email);
        criteria.andEqualTo("userPwd", pwd);
        List<User> users = userdao.selectByExample(example);
        if(CollectionUtils.isEmpty(users))
            return null;
        return users.get(0);
    }

    public Boolean sendVerifyCode(String email) {
        // 生成验证码
        String code = NumberUtils.generateCode(6);
        try {
            // 发送短信
            Map<String, String> msg = new HashMap<>();
            msg.put("email", email);
            msg.put("code", code);
            this.amqpTemplate.convertAndSend("as.verify.exchange", "register.verify", msg);
            // 将code存入redis
            this.redisTemplate.opsForValue().set(KEY_PREFIX + email, code, 30, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public Result delete(String email) {
        Example example = new Example(User.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("email", email);

        userdao.deleteByExample(example);

        return Result.getSuccessInstance();
    }

    public PageResult<User> getAllUsers(Integer page, Integer size) {

        PageHelper.startPage(page, size);

        Page<User> users = (Page<User>)userdao.selectAll();
        PageResult<User> pageResult = new PageResult<>(users.getTotal(), users.getResult());
        return pageResult;
    }

    public PageResult<User> findUsers(String email, String name, Integer page, Integer size) {

        PageHelper.startPage(page, size);

        Example example = new Example(User.class);

        Example.Criteria criteria = example.createCriteria();


        Page<User> users = null;
        if(!StringUtils.isBlank(email) || !StringUtils.isBlank(name)){
            if(!StringUtils.isBlank(email)){
                criteria.orLike("email", "%"+email+"%");
                criteria.orEqualTo("email", email);
            }

            if(!StringUtils.isBlank(name)){
                criteria.orLike("userName", "%"+name+"%");
                criteria.orEqualTo("userName", name);
            }


            users = (Page<User>)userdao.selectByExample(example);
        } else {
            users = (Page<User>)userdao.selectAll();
        }

        PageResult<User> pageResult = new PageResult<>(users.getTotal(), users.getResult());

        return pageResult;
    }

    public Result editUser(String email, String name, String pwd) {

        Example example = new Example(User.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("email", email);

        User user = new User();

        if(!StringUtils.isBlank(name)){
            user.setUserName(name);
        }
        if(!StringUtils.isBlank(pwd)){
                    user.setUserPwd(pwd);
        }
        userdao.updateByExampleSelective(user, example);

        return Result.getSuccessInstance();

    }

    public Result findpwd(String email, String pwd, String verifyCode) {
        String verifyCodeFromRedis = this.redisTemplate.opsForValue().get(KEY_PREFIX + email);
        if(verifyCodeFromRedis == null || verifyCode == null || !verifyCode.equals(verifyCodeFromRedis))
            return new Result("verifyCode error!");
        Example example = new Example(User.class);

        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("email", email);


        User user = new User();
        user.setUserPwd(pwd);

        userdao.updateByExampleSelective(user, example);
        redisTemplate.delete(KEY_PREFIX + user.getEmail());
        return Result.getSuccessInstance();

    }
}
